var express = require('express');
var router = express.Router();
const { sellersModel } = require('../model/sellersModel')
router.get('/getAllSellers', async (req, res) => {
    console.log('=========查询所有的销售员===========');
    const result = await sellersModel.find()
    if (result.length > 0) {
        res.send({
            code: 1,
            rows: result
        })
        console.log(result)
    }
})
router.post('/addSellers', async (req, res) => {
    console.log('=========增加销售员===========')
    try {
        const result = await sellersModel.create(req.body);
        console.log(result)
        if (result) {
            res.send({
                code: 1,
                message: "增加成功",
                data: result
            })
        }
    } catch (err) {
        res.send({
            code: 0,
            message: "增加失败",
        })
        console.log(err)
    }
})

router.delete('/delSellers/:sid', async (req, res) => {
    console.log('=========删除销售员===========')
    const { sid } = req.params
    console.log({ sid });
    try {
        const { deletedCount } = await sellersModel.deleteOne({ sid })
        console.log({ deletedCount })
        if (deletedCount) {
            res.send({
                code: 1,
                message: '销售员删除成功'
            })
        } else {
            res.send({
                code: 0,
                message: '销售员删除失败'
            })
        }
    } catch (err) {
        console.log(err);
        res.send({
            code: -1,
            message: '出现异常'
        })
    }
})

router.put('/modifySellers', async (req, res) => {
    try {
        const { modifiedCount } = await sellersModel.updateOne({ sid: req.body.sid }, req.body)
        if (modifiedCount) {
            res.send({
                code: 1,
                message: '修改成功'

            })
        } else {
            res.send({
                code: 0,
                message: '修改失败'
            })
        }
    } catch (err) {
        res.send({
            code: -1,
            message: "异常出现"
        })
    }
})

router.get('/sellersById/:sid', async (req, res) => {
    const result = await sellersModel.findOne({ sid: req.params.sid })
    if (result) {
        res.send({
            code: 1,
            message: '查询成功',
            data: result
        })
    } else {
        res.send({
            code: 0,
            message: '查询失败'
        })
    }
})

router.get('/searchSellers',async(req,res)=>{
    const result=await sellersModel.find({sellersName:{$regex:req.query.sellersName}})
    if(result.length>0){
        res.send({
            code:1,
            message:'查询成功',
            data:result
        })
    }else{
        res.send({
            code:1,
            message:'查询失败'
        })
    }
  })




module.exports = router;